package com.sskj.b70.v.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;

import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sskj.b70.R;
import com.sskj.b70.common.AnimationUtil;
import com.sskj.b70.common.App;
import com.sskj.b70.common.Constants;
import com.sskj.b70.common.adapter.BaseAdapter;
import com.sskj.b70.common.adapter.ViewHolder;
import com.sskj.b70.common.widget.ToolBarLayout;
import com.sskj.b70.m.bean.CurrencyBean;
import com.sskj.b70.m.bean.Entrust;
import com.sskj.b70.p.activity.EntrustHistoryPresenter;
import com.sskj.b70.utils.NumberUtil;
import com.sskj.b70.utils.ToastUtil;
import com.sskj.b70.v.base.BaseActivity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * 委托历史记录
 * create by Hey at 2018/5/3 8:56
 */
public class EntrustHistoryActivity extends BaseActivity<EntrustHistoryPresenter> {


    @BindView(R.id.entrust_history_toolbar)
    ToolBarLayout entrustHistoryToolbar;
    @BindView(R.id.entrust_history_list)
    RecyclerView entrustHistoryList;
    @BindView(R.id.entrust_history_refresh)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.filter_currency)
    AppCompatSpinner filterCurrency;
    @BindView(R.id.filter_type)
    AppCompatSpinner filterType;
    @BindView(R.id.filter_status)
    AppCompatSpinner filterStatus;
    @BindView(R.id.filer_confirm)
    Button filerConfirm;
    @BindView(R.id.filter_layout)
    LinearLayout filterLayout;
    @BindView(R.id.filter_layout_root)
    LinearLayout filterLayoutRoot;

    private BaseAdapter<Entrust> adapter;


    private String code;
    private String status = null;
    private String type;
    private List<CurrencyBean> currencyBeans = new ArrayList<>();
    private HashMap<String, String> stateMap;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_entrust_history;
    }

    @Override
    public EntrustHistoryPresenter getPresenter() {
        return new EntrustHistoryPresenter();
    }

    @Override
    protected void initView() {
        stateMap = new HashMap<>();
        stateMap.put("0", App.INSTANCE.getString(R.string.strEntrustHistoryActivity1));
        stateMap.put("1", App.INSTANCE.getString(R.string.strEntrustHistoryActivity3));
        stateMap.put("2", App.INSTANCE.getString(R.string.strEntrustHistoryActivity5));
        stateMap.put("3", App.INSTANCE.getString(R.string.strEntrustHistoryActivity7));
        entrustHistoryToolbar.setLeftButtonOnClickLinster(view -> finish());
        refreshLayout.setRefreshHeader(new MaterialHeader(this));
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            refreshLayout.finishRefresh();
            if (status == null) {
                mPresenter.getEntrustListAll(code, status, type);
            } else {
                mPresenter.getEntrustList(code, status, type);
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
        entrustHistoryList.setLayoutManager(layoutManager);
        entrustHistoryList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        adapter = new BaseAdapter<Entrust>(R.layout.item_recycler_entrust_history, new ArrayList<>(), entrustHistoryList, true) {
            @Override
            public void bind(ViewHolder holder, Entrust item) {
                if (item.getStockName() == null || item.getStockName().split("/").length == 1) {
                    item.setStockName("ETH/USDT");
                }
                SpannableString spannableString17 = new SpannableString(item.getStockName());
                RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(0.7F);
                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(
                        Color.parseColor("#AABBCC"));
                StyleSpan styleSpan = new StyleSpan(Typeface.NORMAL);
                spannableString17.setSpan(relativeSizeSpan, item.getNumUnit().length(), item.getStockName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                spannableString17.setSpan(foregroundColorSpan, item.getNumUnit().length(), item.getStockName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                spannableString17.setSpan(styleSpan, item.getNumUnit().length(), item.getStockName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                holder.setText(R.id.entrust_name, spannableString17)
                        .setBackgroundRes(R.id.entrust_state, R.drawable.shape_gray)
                        .setTextColor(R.id.entrust_state, ContextCompat.getColor(EntrustHistoryActivity.this, R.color.bull_light_white))
                        .setText(R.id.entrust_type, item.getTradeType() == 1 ? App.INSTANCE.getString(R.string.strEntrustHistoryActivity11) : App.INSTANCE.getString(R.string.strEntrustHistoryActivity12))
                        .setTextColor(R.id.entrust_type, ContextCompat.getColor(EntrustHistoryActivity.this, item.getTradeType() == 1 ? R.color.market_down : R.color.market_up))
//                        .setText(R.id.item_entrust_time, TimeFormatUtil.SF_FORMAT_G.format(new Date(TimeFormatUtil.parseLongE(item.getCreateTime()))))
                        .setText(R.id.entrust_time, item.getCreateTime() + "")
                        .setText(R.id.entrust_prePrice, NumberUtil.keep4(item.getEntrustPrice() + ""))
                        .setText(R.id.entrust_totalPrice, item.getTotalPrice() + "")
                        .setText(R.id.entrust_preNum, NumberUtil.keepMax(item.getDealNum(), 8))
                        .setText(R.id.entrust_state, stateMap.get(item.getState() + ""))
                        .setText(R.id.entrust_prePrice_text, String.format(App.INSTANCE.getString(R.string.strEntrustHistoryActivity161), item.getPriceUnit()))
                        .setText(R.id.entrust_preNum_text, String.format(App.INSTANCE.getString(R.string.strEntrustHistoryActivity162), item.getNumUnit()))
                        .setText(R.id.entrust_totalPrice_text, App.INSTANCE.getString(R.string.strEntrustHistoryActivity163))
                        .setText(R.id.entrust_realPrice_text, App.INSTANCE.getString(R.string.strEntrustHistoryActivity164) + item.getPriceUnit() + ")")
                        .setText(R.id.entrust_realPrice, item.getDealPrice() + "")
                        .setText(R.id.entrust_realNum_text, App.INSTANCE.getString(R.string.strEntrustHistoryActivity167) + item.getNumUnit() + ")");
                if (item.getBillPriceType() == 1 && item.getTradeType() == 1) {  //市价买入
                    holder.setText(R.id.entrust_realNum, NumberUtil.keepMax(item.getEntrustNum(), 8) + "");//成交数量
                    holder.setText(R.id.entrust_preNum_text, App.INSTANCE.getString(R.string.strEntrustHistoryActivity170));
                    holder.setText(R.id.entrust_preNum, NumberUtil.keep4(item.getTotalPrice()));//委托金额

                } else { //其他

                    holder.setText(R.id.entrust_realNum, NumberUtil.keepMax(item.getEntrustNum(), 8) + "");//成交数量
                    holder.setText(R.id.entrust_preNum_text, App.INSTANCE.getString(R.string.strEntrustHistoryActivity172) + item.getNumUnit() + ")");
                    holder.setText(R.id.entrust_preNum, NumberUtil.keepMax(item.getDealNum(), 8) + "");//委托量

                }
                BigDecimal allBig = new BigDecimal(item.getEntrustNum()).multiply(new BigDecimal(item.getDealPrice()));
                holder.setText(R.id.entrust_totalPrice, NumberUtil.keep4(allBig.toString()));//成交总额
                if (item.getBillPriceType() == 1) {//市价
                    holder.setText(R.id.entrust_prePrice, App.INSTANCE.getString(R.string.strEntrustHistoryActivity33));
                } else {
                    holder.setText(R.id.entrust_prePrice, NumberUtil.keep4(item.getEntrustPrice() + "") + "");
                }

            }
        };
        entrustHistoryList.setAdapter(adapter);

        entrustHistoryToolbar.setRightButtonOnClickLinster(view -> {
            if (filterLayoutRoot.getVisibility() == View.VISIBLE) {
                dismissFilter();
            } else {
                filterLayoutRoot.setVisibility(View.VISIBLE);
                filterLayoutRoot.startAnimation(AnimationUtil.createAlphaVisible());
            }
        });
    }

    @Override
    protected void initData() {
//        code = getIntent().getStringExtra(Constants.CODE);
        mPresenter.getCurrencyList();
        mPresenter.getEntrustListAll(code, null, null);
    }

    /**
     * 设置列表
     *
     * @param data 数据源
     */
    public void setData(List<Entrust> data) {
        adapter.setNewData(data);
    }


    /**
     * 启动
     *
     * @param context context
     */
    public static void start(Context context, String code) {
        Intent intent = new Intent(context, EntrustHistoryActivity.class);
        intent.putExtra(Constants.CODE, code);
        context.startActivity(intent);
    }


    /**
     * 取消订单
     *
     * @param message 返回信息
     * @param success 是否成功取消
     */
    public void cancelOrder(String message, boolean success) {
        ToastUtil.showShort(message);
        if (success) {
            if (status == null) {
                mPresenter.getEntrustListAll(code, status, type);
            } else {
                mPresenter.getEntrustList(code, status, type);
            }
        }
    }

    public void initFilter() {
        ArrayList<String> items = new ArrayList<>();
        items.add(App.INSTANCE.getString(R.string.strEntrustHistoryActivity36));
        for (CurrencyBean c : currencyBeans) {
            items.add(c.getName());
        }
        ArrayAdapter<String> currencyAdapter = new ArrayAdapter<String>(this, R.layout.dropdown_item, items);

        ArrayAdapter statusAdapter = new ArrayAdapter(this, R.layout.dropdown_item, getResources().getStringArray(R.array.orderStatus));
        ArrayAdapter typeAdapter = new ArrayAdapter(this, R.layout.dropdown_item, getResources().getStringArray(R.array.orderType));
        filterCurrency.setAdapter(currencyAdapter);
        filterStatus.setAdapter(statusAdapter);
        filterType.setAdapter(typeAdapter);
        Button confirm = findViewById(R.id.filer_confirm);
        confirm.setOnClickListener(v -> {
            if (filterCurrency.getSelectedItemPosition() == 0) {
                code = null;
            } else {
                code = currencyBeans.get(filterCurrency.getSelectedItemPosition() - 1).getName();
            }

            if (filterType.getSelectedItemPosition() == 0) {

                type = null;
            } else {
                type = filterType.getSelectedItemPosition() + "";
            }
            switch (filterStatus.getSelectedItemPosition()) {
                case 0:
                    status = null;
                    break;
                case 1:
                case 2:
                    status = filterStatus.getSelectedItemPosition() + 1 + "";
                    break;

            }
            if (status == null) {
                mPresenter.getEntrustListAll(code, "2,3", type);
            } else {
                mPresenter.getEntrustList(code, status, type);
            }
            dismissFilter();
        });
    }


    public void setFilter(List<CurrencyBean> data) {
        currencyBeans = data;
        runOnUiThread(() -> initFilter());

    }

    private void dismissFilter() {
        filterLayoutRoot.startAnimation(AnimationUtil.createAlphaGone());
        filterLayoutRoot.postDelayed(() -> filterLayoutRoot.setVisibility(View.GONE), AnimationUtil.ANIMATION_OUT_TIME);
    }
}
